package com.ckw.question.controller;

import com.ckw.judger.pojo.TestPack;
import com.ckw.judger.pojo.TestResult;
import com.ckw.question.config.RabbitMQConfiguration;
import com.ckw.question.pojo.Type;
import com.ckw.question.server.impl.JudgeServerImpl;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class JudgeConsumer {
//    private static final Logger log = LoggerFactory.getLogger(JudgeConsumer.class);

    @Autowired
    private JudgeServerImpl judgeServer;

    @Autowired
    private RabbitTemplate rabbitTemplate; // 注入 RabbitTemplate
    @RabbitListener(queues = RabbitMQConfiguration.JUDGE_QUEUE, containerFactory = "rabbitListenerContainerFactory")
    public void listen(TestPack testPack, Message message, Channel channel) throws IOException {
        // 处理逻辑
        long tag = message.getMessageProperties().getDeliveryTag();
        TestResult testResult = null;
        try {
            boolean setting = false;

            if (testPack.getType().equals(Type.MATCH)) {
                testResult = judgeServer.matchJudge(testPack);
                setting = judgeServer.settingForMatch(testResult, testPack);
                log.info("竞赛提交");
            } else if (testPack.getType().equals(Type.NORMAL)) {
                log.info("普通提交");
                testResult = judgeServer.normalJudge(testPack);
                setting = judgeServer.setting(testResult, testPack);
                setting = judgeServer.mustSetting(testResult, testPack);
            } else {
                log.error("提交失败, 没有这个提交选项");
            }
            channel.basicAck(tag, false);
        } catch (Exception e) {
            log.error("Consumer2 处理消息失败: " + message, e);
            Boolean redelivered = message.getMessageProperties().getRedelivered();
            if(redelivered) {
                // 如果是重复投递不再进入队列
                channel.basicNack(tag, false, false);
            } else {
                // 否则重新进入队列
                channel.basicNack(tag, false, true);
            }
        }

        // 获取生产者的 replyTo 队列
        String replyTo = message.getMessageProperties().getReplyTo();

        // 获取请求消息的关联头
        String correlationId = message.getMessageProperties().getCorrelationId();

        // 创建响应消息的属性，并设置关联头
        MessageProperties replyProps = new MessageProperties();
        replyProps.setReplyTo(replyTo);
        replyProps.setCorrelationId(correlationId);

        // 创建响应消息
        Message replyMessage = rabbitTemplate.getMessageConverter().toMessage(testResult, replyProps);

        // 将结果发送到生产者的 replyTo 队列
        rabbitTemplate.send("", replyTo, replyMessage);
    }

    @RabbitListener(queues = RabbitMQConfiguration.TEST_QUEUE)
    public void Consumer2(String dataMessage, Message message, Channel channel) throws IOException {
        long tag = message.getMessageProperties().getDeliveryTag();
        try {
            // 业务处理逻辑
            log.info("Consumer2 处理消息: " + dataMessage);
            Thread.sleep(200);
            channel.basicAck(tag, false);
        } catch (Exception e) {
            log.error("Consumer2 处理消息失败: " + message, e);
            Boolean redelivered = message.getMessageProperties().getRedelivered();
            if(redelivered) {
                // 如果是重复投递不再进入队列
                channel.basicNack(tag, false, false);
            } else {
                // 否则重新进入队列
                channel.basicNack(tag, false, true);
            }
        }
    }

    // 添加死信队列监听器
    @RabbitListener(queues = RabbitMQConfiguration.DEAD_LETTER_QUEUE)
    public void handleDlxMessage(Message message, Channel channel) throws IOException {
        //long tag = message.getMessageProperties().getDeliveryTag();

        // 使用合适的字符编码将字节数组转换为字符串，这里使用UTF-8

        try {
           // byte[] body = message.getBody();
            //String dataMessage = new String(body, StandardCharsets.UTF_8);
            //log.info("收到死信消息: " + dataMessage);
            // 确认消息
            //channel.basicAck(tag, false);
            //log.info("handleDlxMessage 死信完成处理: " + dataMessage);
        } catch (Exception e) {
//            log.error("handleDlxMessage 死信处理消息失败: " + message, e);
//            Boolean redelivered = message.getMessageProperties().getRedelivered();
//            if(redelivered) {
//                // 如果是重复投递不再进入队列
//                channel.basicNack(tag, false, false);
//            } else {
////                 否则重新进入队列
//                channel.basicNack(tag, false, true);
//            }
        }
    }

//    @RabbitListener(queues = RabbitMQConfiguration.DELAYED_QUEUE)
//    public void processMessageDelay(String dataString, Message message, Channel channel) throws IOException {
//        log.info("[delay message" + dataString);
//        log.info("[delay message[当前时间]" + new SimpleDateFormat("HH:mm:ss").format(new Date()));
//        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
//    }
}
